<template>
  <div
    v-loading="getListLoading"
    class="warehouse-in-list-wrapper"
    element-loading-text="加载中..."
  >
    <status-tabs @change-status="changeStatus" />
    <div class="warehouse-in-list">
      <div class="header">
        <div>
          <HPlainButton
            v-if="getListParam.orderState === 1"
            v-permission="'inbound_listAudit'"
            @click="batchAudit()"
            >批量审核</HPlainButton
          >
          <h-plain-button
            v-if="getListParam.orderState === 0"
            v-permission="'inbound_return'"
            :disabled="selectData.length === 0"
            @click="multipleReturnModalVisible = true"
            >批量退回</h-plain-button
          >
          <!-- <router-link to="/storage/newin">
            <HPlainButton> 新增入库 </HPlainButton>
          </router-link> -->
        </div>
        <div class="search">
          <!-- 日期类型 -->
          <div class="search-item date-type">
            <el-select
              v-model="getListParam.dateType"
              clearable
              placeholder="日期类型"
              @change="onDateTypeChange"
              @clear="_getList"
            >
              <el-option
                v-for="item in dateType"
                :key="item.value"
                :label="item.title"
                :value="item.value"
              />
            </el-select>
          </div>

          <!-- 日期范围 -->
          <div v-if="getListParam.dateType === 1" class="search-item date-range">
            <date-range
              ref="dateRangeRef"
              :start-date-placeholder="'开始日期'"
              :end-date-placeholder="'结束日期'"
              @change="handleDateChange"
            />
          </div>

          <!-- 单据来源 -->
          <div class="search-item source">
            <el-select
              v-model="getListParam.source"
              clearable
              placeholder="单据来源"
              @change="_getList"
              @clear="_getList"
            >
              <el-option
                v-for="item in sourceList"
                :key="item.value"
                :label="item.title"
                :value="item.value"
              />
            </el-select>
          </div>

          <!-- 入库单状态 -->
          <div class="search-item status">
            <el-select
              v-model="getListParam.orderState"
              clearable
              placeholder="入库单状态"
              @change="_getList"
              @clear="_getList"
            >
              <el-option
                v-for="item in status"
                :key="item.value"
                :label="item.title"
                :value="item.value"
              />
            </el-select>
          </div>

          <!-- 单据类型 -->
          <!-- <div class="search-item receipts_type">
            <el-select
              v-model="getListParam.typeId"
              :remote-method="handleGetWarehouseInTypeOptions"
              clearable
              filterable
              placeholder="单据类型"
              :loading="getWarehouseTypeOptionsLoading"
              @change="_getList"
              @clear="_getList"
            >
              <el-option
                v-for="(item, index) in warehouseInTypeOptions"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div> -->

          <!-- 网点名称 -->
          <div class="search-item receipts_type">
            <el-select
              v-model="getListParam.networkId"
              :remote-method="handleGetWarehouseInNetworkOptions"
              clearable
              filterable
              placeholder="网点名称"
              :loading="getWarehouseNetworkOptionsLoading"
              @change="_getList"
              @clear="_getList"
            >
              <el-option
                v-for="(item, index) in warehouseInNetworkOptions"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>

          <!-- 工单号 -->
          <div class="search-item input">
            <el-input
              v-model.trim="getListParam.workNo"
              clearable
              placeholder="工单号"
              @keyup.enter="_getList"
              @clear="_getList"
            >
            </el-input>
          </div>

          <!-- 入库单号/制单人 -->
          <div class="search-item input">
            <el-input
              v-model.trim="getListParam.code"
              clearable
              placeholder="入库单号/制单人"
              @keyup.enter="_getList"
              @clear="_getList"
            >
            </el-input>
          </div>

          <!--搜索按钮-->
          <HButton type="primary" @click="_getList">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </HButton>

          <!--重置按钮-->
          <HButton @click="onReset">
            <el-icon>
              <RefreshRight />
            </el-icon>
            重置
          </HButton>
        </div>
      </div>
      <div class="table">
        <el-table
          :data="list"
          :border="true"
          height="100%"
          resizable
          stripe
          :summary-method="getSummaries"
          show-summary
          @selection-change="handleChange"
        >
          <!--选择-->
          <el-table-column type="selection" width="40" :align="'center'" />

          <!-- 序号 -->
          <el-table-column fixed="left" :align="'center'" label="序号" type="index" width="60" />

          <!-- 入库单号 -->
          <el-table-column fixed label="入库单号" prop="code" show-overflow-tooltip min-width="130">
            <template #default="scope">
              <HLink @click="onDetailCLick(scope.row.id)">{{ scope.row.code }}</HLink>
            </template>
          </el-table-column>

          <!-- 工单号 -->
          <el-table-column label="工单号" prop="workNo" show-overflow-tooltip min-width="150">
            <!-- <template  #default="scope">
              <HLink @click="goOrderDetail(scope.row)">{{ scope.row.workNo }}</HLink>
            </template> -->
          </el-table-column>

          <!-- 网点名称 -->
          <el-table-column
            label="网点名称"
            prop="networkName"
            show-overflow-tooltip
            min-width="150"
          />

          <!-- 仓库名称 -->
          <el-table-column label="仓库名称" prop="store" show-overflow-tooltip min-width="150" />

          <!-- 退回数量 -->
          <el-table-column label="退回数量" prop="qty" show-overflow-tooltip min-width="150" />

          <!-- 仓库类型 -->
          <!-- <el-table-column label="仓库类型" show-overflow-tooltip width="90">
            <template #default="{ row }">
              {{ getWarehouseTypeTxt(row.storeType) }}
            </template>
          </el-table-column> -->

          <!-- 入库类型 -->
          <el-table-column label="入库类型" prop="type" show-overflow-tooltip width="120" />

          <!-- 单据来源 -->
          <el-table-column label="单据来源" show-overflow-tooltip width="100">
            <template #default="{ row }">
              {{ getSourceTxt(row.source) }}
            </template>
          </el-table-column>

          <!-- 制单人 -->
          <el-table-column label="制单人" prop="createEmp" show-overflow-tooltip width="80" />

          <!-- 制单时间 -->
          <el-table-column label="制单时间" prop="gmtCreate" show-overflow-tooltip width="128" />

          <!-- 审核时间 -->
          <el-table-column label="审核时间" prop="applyTime" show-overflow-tooltip width="128" />

          <!-- 入库单状态 -->
          <el-table-column
            label="入库单状态"
            prop="orderState"
            width="86"
            :align="'center'"
            fixed="right"
          >
            <template #default="scope">
              <div class="flex_justify_center">
                <HStatus v-if="scope.row.orderState == 0" type="warning">待退回</HStatus>
                <HStatus v-if="scope.row.orderState == 1" type="warning">在途中</HStatus>
                <HStatus v-if="scope.row.orderState == 2" type="success">已退回</HStatus>
              </div>
            </template>
          </el-table-column>

          <!-- 操作 -->
          <el-table-column label="操作" fixed="right" width="100">
            <template #default="scope">
              <div style="display: flex; gap: 10px">
                <h-link
                  v-if="scope.row.orderState == 1"
                  v-permission="'inbound_listAudit'"
                  @click="onAudit(scope.row.id)"
                  >审核</h-link
                >
                <h-link @click="onDetailCLick(scope.row.id)">详情</h-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <Pagination
          ref="paginationInstance"
          :list_total="listTotal"
          @size-change="_getList"
          @current-change="_getList"
        />
      </div>
    </div>

    <multiple-return-modal
      v-model="multipleReturnModalVisible"
      :id-list="selectData.map((item) => item.id)"
      @update="_getList"
    />
  </div>
</template>

<script lang="ts" setup>
  import Pagination from '@/components/Pagination/index.vue'
  import { onMounted, ref } from 'vue'
  import { Search, RefreshRight } from '@element-plus/icons-vue'
  import DateRange from '@/components/business/date-range/DateRange.vue'
  import { useRouter } from 'vue-router'
  import routeComponentName from '@/config/route-component-name'
  import {
    useGetWarehouseInList,
    useGetWarehouseInOptions,
  } from '@/services/pages/storage/useWarehouseInbound'
  import StatusTabs from './components/StatusTabs/index'
  import _ from 'lodash'
  import { ElMessage, ElMessageBox, TableColumnCtx } from 'element-plus'
  import { HMessageBox } from '@/components/common/message'
  import MultipleReturnModal from './components/multiple-return-modal/index.vue'

  const { list, listTotal, getListParam, getListLoading, getList, resetGetListParam, audit } =
    useGetWarehouseInList()
  const {
    options: warehouseInNetworkOptions,
    getOptionsParam: getWarehouseNetworkOptionsParam,
    getOptionsLoading: getWarehouseNetworkOptionsLoading,
    getOptions: getWarehouseNetworkOptions,
  } = useGetWarehouseInOptions()

  defineOptions({
    name: routeComponentName.storage.inStorageList,
  })

  // 批量退回弹窗显示状态
  const multipleReturnModalVisible = ref(false)

  // 去啊奴据路由对象
  const router = useRouter()

  // 日期范围选择组件实例
  const dateRangeRef = ref<InstanceType<typeof DateRange> | null>(null)

  // 分页组件实例
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 日期类型
  const dateType = ref([
    { title: '今天', value: 2 },
    { title: '本周', value: 3 },
    { title: '本月', value: 4 },
    { title: '自定义时间', value: 1 },
  ])

  // 单据来源
  const sourceList = ref([
    { title: '系统单', value: 1 },
    { title: '工单', value: 2 },
    { title: 'ERP单据', value: 3 },
    { title: '仓库移动端单据', value: 4 },
    { title: '第三方系统单据', value: 5 },
  ])

  // 出库单状态
  const status = ref([
    { title: '待退回', value: 0 },
    { title: '在途中', value: 1 },
    { title: '已退回总部', value: 2 },
  ])

  // 仓库类型
  const warehouseTypeList = ref([
    { title: '内部仓库', value: 0 },
    { title: '网点-外部仓库', value: 1 },
    { title: '工程师-外部仓库', value: 2 },
  ])

  /**
   * 获取表格合计
   * @param {object} param 事件参数
   */
  const getSummaries = (param: {
    columns: TableColumnCtx<WarehouseInListItem>[]
    data: Array<WarehouseInListItem>
  }) => {
    const result: Array<string> = []
    result[1] = '合计'
    for (let i = 0; i < param.columns.length; i++) {
      const column = param.columns[i]
      if (column.property === 'qty') {
        result[i] = param.data.reduce((prev, current) => prev + Number(current.qty), 0).toString()
      }
    }
    return result
  }

  /**
   * 获取仓库类型文本
   * @param {(0|1|2)} type - 仓库类型
   */
  const getWarehouseTypeTxt = (type: 0 | 1 | 2) => {
    const warehouseType = warehouseTypeList.value.find((item) => item.value === type)
    if (warehouseType) {
      return warehouseType.title
    }
    return ''
  }

  /**
   * 获取单据来源文本
   * @param {(1|2|3|4|5)} type - 单据来源
   */
  const getSourceTxt = (type: 1 | 2 | 3 | 4 | 5) => {
    const source = sourceList.value.find((item) => item.value === type)
    if (source) {
      return source.title
    }
    return ''
  }

  /**
   * 获取列表
   */
  const _getList = () => {
    if (paginationInstance.value) {
      getListParam.value.limit = paginationInstance.value.size
      getListParam.value.page = paginationInstance.value.current
      getList()
    }
  }

  /**
   * 详情点击、单号点击时触发
   * @param id - id
   */
  const onDetailCLick = (id: number) => {
    router.push('/storage/inbound/detail/' + id)
  }

  /**
   * 获取网点下拉选项
   * @param {String} keyword - 搜索关键字
   */
  const handleGetWarehouseInNetworkOptions = _.debounce((keyword: string) => {
    if (getWarehouseNetworkOptionsParam.value.name !== keyword) {
      getWarehouseNetworkOptionsParam.value.name = keyword
      getWarehouseNetworkOptions()
    }
  }, 600)

  /**
   * 时间类型更新事件
   */
  const onDateTypeChange = () => {
    if (getListParam.value.dateType !== 1) {
      _getList()
    }
  }

  /**
   * 日期更新事件
   * @param {Object} param - 日期范围
   * @param {String} param.startDate - 开始日期
   * @param {String} param.endDate - 结束日期
   */
  const handleDateChange = (param: { startDate: string; endDate: string }) => {
    if (param.startDate && param.startDate) {
      getListParam.value.startTime = param.startDate
      getListParam.value.endTime = param.endDate
      _getList()
    }
  }

  const selectData = ref<Array<WarehouseOldPartReturn>>([])
  // 勾选
  const handleChange = (e: Array<WarehouseOldPartReturn>) => {
    selectData.value = e
  }
  // 审核
  const onAudit = (id) => {
    batchAudit(id)
  }
  // 批量审核
  const batchAudit = (id) => {
    if (!id && !selectData.value.length) {
      HMessageBox.error('请勾选审核的数据')
      return
    }
    ElMessageBox({
      title: '提示',
      message: '确认审核？',
      type: 'warning',
      showCancelButton: true,
      cancelButtonText: '取消',
      async beforeClose(action, instance, done) {
        if (['close', 'cancel'].includes(action)) {
          done()
        }

        if (action === 'confirm') {
          done()
          audit(id ? [id] : selectData.value.map((item) => item.id)).then((res) => {
            if (res.code == 20000) {
              ElMessage({
                type: 'success',
                message: '审核成功',
                duration: 5000,
              })
              _getList()
            }
          })
        }
      },
    })
  }
  // 选择tab 状态
  const changeStatus = (val) => {
    getListParam.value.orderState = val
    _getList()
  }

  /**
   * 重置事件
   */
  const onReset = () => {
    resetGetListParam()
    if (dateRangeRef.value) {
      dateRangeRef.value.clearDate()
    }
    _getList()
  }

  /**
   * 工单单号点击事件
   * @param {string} orderId - 工单id
   */
  const goOrderDetail = (orderId: string) => {
    if (orderId) {
      router.push(`/order/odetail/${orderId}`)
    }
  }

  onMounted(() => {
    getWarehouseNetworkOptions()
    _getList()
  })
</script>

<style lang="scss" scoped>
  .warehouse-in-list-wrapper {
    height: calc(100vh - 92px);
    box-sizing: border-box;
    padding: 12px;
    display: flex;
    flex-direction: column;

    .warehouse-in-list {
      height: 100%;
      box-sizing: border-box;
      padding: 12px;
      display: flex;
      flex-direction: column;
      row-gap: 12px;
      background-color: #fff;
      flex: 1;
      height: 0;

      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        row-gap: 12px;

        .search {
          height: 28px;
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          gap: 5px;

          .date-type {
            width: 110px;
          }

          .date-range {
            width: 260px;
          }

          .source {
            width: 130px;
          }

          .status {
            width: 110px;
          }

          .receipts_type {
            width: 100px;
          }

          .input {
            width: 140px;
          }
        }
      }

      .table {
        max-height: calc(100% - 80px);
      }

      .pagination {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
</style>
